package record

import (
	"context"
	pb "gitee.com/kailun_iot/grpc_interface/gosdk/record"
	"gitee.com/kailun_iot/utils/auth"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/status"
	"strings"
	"time"
)

const (
	DbName         = "sa_cloud"
	DevManager     = 1
	DevOperate     = 2
	GatewayManager = 3
	UserManager    = 4
	WebAccess      = 5
	SceneManager   = 6
	SceneOperate   = 7
)

func AddRecord(dbClient *mongo.Client, ctx context.Context, recordType uint32, txt string) (string, error) {
	//解析token
	claims, err := auth.DecodeClaimsFromRequest(ctx)
	if err != nil {
		return "", status.Error(codes.Unauthenticated, "")
	}
	if claims.Id == "root" { //root用户不保存记录
		return "", nil
	}
	md, _ := metadata.FromIncomingContext(ctx)
	//获取ip
	ip := strings.Split(md.Get("x-forwarded-for")[0], ",")[0]
	//装载数据
	record := pb.RecordModel{
		RecordType: recordType, Txt: txt,
		Ip: ip, ProjectId: claims.Subject, UserId: claims.Id,
		Id: primitive.NewObjectID().Hex(), CreateTime: time.Now().Unix(),
	}
	//保持到数据库
	collection := dbClient.Database(DbName).Collection("record")
	_, err = collection.InsertOne(context.Background(), &record)
	return record.Id, err
}
